var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Goods = require('../models/goods');

mongoose.connect('mongodb://127.0.0.1:27017/demo1');

mongoose.connection.on('connected', function() {
    console.log('connect success');
});

mongoose.connection.on('error', function() {
    console.log('connect error');
});

mongoose.connection.on('disconnected', function() {
    console.log('connect disconnected');
});

// var errFunc = function(params) {
//     console.log(params.msg)
//     var status = params.status || '1';
//     params.res.json({
//         status,
//         msg: params.msg
//     });
// }

// 商品列表操作
router.get('/', function(req, res, next) {
    // req.param() => 获取参数;skip() => 查询跳过
    let sort = req.param('sort');
    let page = parseInt(req.param('page'));
    let pageSize = parseInt(req.param('pageSize'));
    let priceLeve = req.param('priceLeve');
    let skip = (page - 1) * pageSize;
    let params = {};
    var priceGt = '', priceLte = '';
    if (priceLeve != 'all') {
        switch (priceLeve) {
            case '0': priceGt = 0;priceLte = 100;break;
            case '1': priceGt = 100;priceLte = 500;break;
            case '2': priceGt = 500;priceLte = 1000;break;
            case '3': priceGt = 1000;priceLte = 3000;break;
        }
        params = {
            salePrice: {
                $gt: priceGt,
                $lte: priceLte
            }
        }
    }
    let goodsModel = Goods.find(params).skip(skip).limit(pageSize);
    goodsModel.sort({ 'salePrice': sort });
    goodsModel.exec(function(err, doc) {
        if (err) {
            res.json({
                status: '1',
                msg: err.message,
            });
        } else {
            res.json({
                status: '0',
                msg: '',
                result: {
                    count: doc.length,
                    list: doc
                }
            })
        }
    });
});

// 添加购物车
router.post('/addCart', function(req, res, next) {
    let userId = '001';
    let productId = req.body.productId;
    let User = require('../models/user');

    // 查询当前用户
    User.findOne({ userId: userId }, function(err, userDoc) {
        if (err) {
            res.json({
                status: '1',
                msg: err.message
            });
        } else {
            if (userDoc) {
                let goodItem = '';
                userDoc.cartList.forEach(function(item) {
                    if (item.productId == productId) {
                        goodItem = item;
                        item.productNum ++;
                    }
                });
                if (goodItem) { // 当前商品已添加，商品数加1，保存
                    userDoc.save(function(err2, doc2) {
                        if (err2) {
                            res.json({
                                status: '1',
                                msg: err2.message
                            });
                        } else {
                            res.json({
                                status: '0',
                                msg: '',
                                result: 'success'
                            });
                        }
                    })
                } else { // 当前商品未添加，插入新数据
                    Goods.findOne({ productId: productId }, function(err1, doc1) {
                        if (err1) {
                            res.json({
                                status: '1',
                                msg: err1.message
                            });
                        } else {
                            if (doc1) {
                                doc1.productNum = 1;
                                doc1.checked = 1;
                                
                                userDoc.cartList.push(doc1);
                                userDoc.save(function(err2, doc2) {
                                    if (err2) {
                                        res.json({
                                            status: '1',
                                            msg: err2.message
                                        });
                                    } else {
                                        res.json({
                                            status: '0',
                                            msg: '',
                                            result: 'success'
                                        });
                                    }
                                })
                            }
                        }
                    });
                }
            }
        }
    });
});
module.exports = router;